package org.example.xx2.service;

import org.example.xx2.dto.*;
import org.example.xx2.mapper.UserMapper;
import org.example.xx2.model.User;
import org.example.xx2.util.JwtUtil;
import org.example.xx2.util.PasswordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    @Autowired
    private PasswordUtil passwordUtil;
    
    @Autowired
    private VerificationCodeService verificationCodeService;
    
    @Autowired
    private EmailService emailService;

    @Override
    public ApiResponse<LoginResponse> login(LoginRequest request) {
        if (!StringUtils.hasText(request.getAccount()) || !StringUtils.hasText(request.getPassword())) {
            return ApiResponse.error("用户名和密码不能为空");
        }
        User user = userMapper.findByUsername(request.getAccount());
        if (user == null) {
            return ApiResponse.error("用户不存在");
        }
        if (!passwordUtil.matches(request.getPassword(), user.getPassword())) {
            return ApiResponse.error("密码错误！");
        }
        String token = jwtUtil.generateToken(user.getAccount(), String.valueOf(user.getRole()));
        // 创建登录响应对象，包含token和角色信息
        LoginResponse response = new LoginResponse();
        response.setToken(token);
        response.setRole(user.getRole());

        return ApiResponse.success("登录成功",response);
    }

    @Override
    public ApiResponse<String> register(RegisterRequest request) {
        if (!request.getPassword().equals(request.getConfirmPassword())) {
            return ApiResponse.error("两次输入的密码不一致");
        }
        if (isUsernameExists(request.getAccount())) {
            return ApiResponse.error("用户名已存在");
        }
        if (StringUtils.hasText(request.getPhone()) && isPhoneExists(request.getPhone())) {
            return ApiResponse.error("手机号已存在");
        }
        if (StringUtils.hasText(request.getEmail()) && isEmailExists(request.getEmail())) {
            return ApiResponse.error("邮箱已存在");
        }
        User user = new User();
        user.setAccount(request.getAccount());
        user.setPassword(passwordUtil.encodePassword(request.getPassword()));
        user.setName(request.getName());
        user.setAge(request.getAge());
        user.setPhone(request.getPhone());
        user.setEmail(request.getEmail());
        user.setSex(request.getSex());
        user.setQuestion(request.getQuestion());
        user.setAsw(request.getAsw());
        user.setRole(1); // 普通用户
        user.setDel(0);
        user.setCreateTime(java.time.LocalDateTime.now());
        user.setUpdateTime(java.time.LocalDateTime.now());
        int result = userMapper.insert(user);
        if (result > 0) {
            return ApiResponse.success("注册成功，请登录");
        } else {
            return ApiResponse.error("注册失败，请重试");
        }
    }

    @Override
    public ApiResponse<String> getSecurityQuestion(String account) {
        User user = userMapper.findByUsername(account);
        if (user == null) {
            return ApiResponse.error("用户不存在");
        }
        if (!StringUtils.hasText(user.getQuestion())) {
            return ApiResponse.error("该用户未设置安全问题");
        }
        return ApiResponse.success(user.getQuestion());
    }

    @Override
    public ApiResponse<String> verifySecurityAnswer(ForgotPasswordRequest request) {
        User user = userMapper.findByUsername(request.getAccount());
        if (user == null) {
            return ApiResponse.error("用户不存在");
        }
        if (!StringUtils.hasText(user.getAsw()) || !user.getAsw().equals(request.getAsw())) {
            return ApiResponse.error("安全问题答案错误");
        }
        return ApiResponse.success("验证成功");
    }

    @Override
    public ApiResponse<String> sendPhoneVerificationCode(String phone) {
        User user = userMapper.findByPhone(phone);
        if (user == null) {
            return ApiResponse.error("该手机号未注册");
        }

        String code = verificationCodeService.generateCode();
        verificationCodeService.saveCode(phone, code);

        // 这里应该调用短信服务发送验证码
        // 为了演示，我们直接返回验证码
        return ApiResponse.success("验证码已发送", code);
    }

    @Override
    public ApiResponse<String> sendEmailVerificationCode(String email) {
        User user = userMapper.findByEmail(email);
        if (user == null) {
            return ApiResponse.error("该邮箱未注册");
        }

        String code = verificationCodeService.generateCode();
        verificationCodeService.saveCode(email, code);

        // 发送邮件验证码
        emailService.sendVerificationCode(email, code);

        return ApiResponse.success("验证码已发送到邮箱");
    }

    @Override
    public ApiResponse<String> resetPasswordByCode(ForgotPasswordRequest request) {
        // 验证新密码一致性
        if (!request.getNewPassword().equals(request.getConfirmPassword())) {
            return ApiResponse.error("两次输入的密码不一致");
        }
        
        // 验证验证码
        String key = "";
        if ("PHONE".equals(request.getType())) {
            key = request.getPhone();
        } else if ("EMAIL".equals(request.getType())) {
            key = request.getEmail();
        }
        
        if (!verificationCodeService.verifyCode(key, request.getVerificationCode())) {
            return ApiResponse.error("验证码错误或已过期");
        }
        
        // 查找用户
        User user = null;
        if ("PHONE".equals(request.getType())) {
            user = userMapper.findByPhone(request.getPhone());
        } else if ("EMAIL".equals(request.getType())) {
            user = userMapper.findByEmail(request.getEmail());
        }
        
        if (user == null) {
            return ApiResponse.error("用户不存在");
        }
        
        // 更新密码
        String encodedPassword = passwordUtil.encodePassword(request.getNewPassword());
        LocalDateTime now = java.time.LocalDateTime.now();
        int result = userMapper.updatePassword(user.getId(), encodedPassword,now);
        
        if (result > 0) {
            // 发送密码重置成功邮件
            if (StringUtils.hasText(user.getEmail())) {
                emailService.sendPasswordResetSuccess(user.getEmail(), user.getAccount());
            }
            return ApiResponse.success("密码重置成功");
        } else {
            return ApiResponse.error("密码重置失败");
        }
    }

    @Override
    public ApiResponse<String> changePassword(Integer userId, ChangePasswordRequest request) {
        // 验证新密码一致性
        if (!request.getNewPassword().equals(request.getConfirmPassword())) {
            return ApiResponse.error("两次输入的密码不一致");
        }
        
        // 获取用户信息
        User user = userMapper.findById(userId);
        if (user == null) {
            return ApiResponse.error("用户不存在");
        }
        
        // 验证原密码
        if (!passwordUtil.matches(request.getOldPassword(), user.getPassword())) {
            return ApiResponse.error("原密码错误");
        }
        
        // 检查新密码是否与原密码相同
        if (passwordUtil.matches(request.getNewPassword(), user.getPassword())) {
            return ApiResponse.error("新密码不能与原密码相同");
        }
        
        // 更新密码
        String encodedPassword = passwordUtil.encodePassword(request.getNewPassword());
        int result = userMapper.updatePassword(userId, encodedPassword,LocalDateTime.now());
        
        if (result > 0) {
            return ApiResponse.success("密码修改成功");
        } else {
            return ApiResponse.error("密码修改失败");
        }
    }

    @Override
    public ApiResponse<User> getUserInfo(Integer userId) {
        User user = userMapper.findById(userId);
        if (user == null) {
            return ApiResponse.error("用户不存在");
        }
        
        // 不返回密码
        user.setPassword(null);
        return ApiResponse.success(user);
    }

    @Override
    public ApiResponse<String> updateUserInfo(Integer userId, User user) {
        User existingUser = userMapper.findById(userId);
        if (existingUser == null) {
            return ApiResponse.error("用户不存在");
        }
        
        // 检查手机号是否被其他用户使用
        if (StringUtils.hasText(user.getPhone()) && 
            !user.getPhone().equals(existingUser.getPhone()) && 
            isPhoneExists(user.getPhone())) {
            return ApiResponse.error("手机号已被其他用户使用");
        }
        
        // 检查邮箱是否被其他用户使用
        if (StringUtils.hasText(user.getEmail()) && 
            !user.getEmail().equals(existingUser.getEmail()) && 
            isEmailExists(user.getEmail())) {
            return ApiResponse.error("邮箱已被其他用户使用");
        }
        
        // 更新用户信息
        user.setId(userId);
        user.setUpdateTime(java.time.LocalDateTime.now());
        int result = userMapper.update(user);
        
        if (result > 0) {
            return ApiResponse.success("用户信息更新成功");
        } else {
            return ApiResponse.error("用户信息更新失败");
        }
    }

    @Override
    public ApiResponse<List<User>> getAllUsers() {
        List<User> users = userMapper.findAll();
        // 不返回密码
        users.forEach(user -> user.setPassword(null));
        return ApiResponse.success(users);
    }

    @Override
    public ApiResponse<List<User>> getUsersByPage(int page, int size) {
        int offset = (page - 1) * size;
        List<User> users = userMapper.findByPage(offset, size);
        // 不返回密码
        users.forEach(user -> user.setPassword(null));
        return ApiResponse.success(users);
    }

    @Override
    public ApiResponse<String> updateUserByAdmin(Integer userId, User user) {
        User existingUser = userMapper.findById(userId);
        if (existingUser == null) {
            return ApiResponse.error("用户不存在");
        }
        
        // 检查手机号是否被其他用户使用
        if (StringUtils.hasText(user.getPhone()) && 
            !user.getPhone().equals(existingUser.getPhone()) && 
            isPhoneExists(user.getPhone())) {
            return ApiResponse.error("手机号已被其他用户使用");
        }
        
        // 检查邮箱是否被其他用户使用
        if (StringUtils.hasText(user.getEmail()) && 
            !user.getEmail().equals(existingUser.getEmail()) && 
            isEmailExists(user.getEmail())) {
            return ApiResponse.error("邮箱已被其他用户使用");
        }
        
        // 更新用户信息
        user.setId(userId);
        user.setUpdateTime(java.time.LocalDateTime.now());
        int result = userMapper.update(user);
        
        if (result > 0) {
            return ApiResponse.success("用户信息更新成功");
        } else {
            return ApiResponse.error("用户信息更新失败");
        }
    }

    @Override
    public ApiResponse<String> deleteUser(Integer userId) {
        User user = userMapper.findById(userId);
        if (user == null) {
            return ApiResponse.error("用户不存在");
        }
        
        int result = userMapper.deleteById(userId);
        if (result > 0) {
            return ApiResponse.success("用户删除成功");
        } else {
            return ApiResponse.error("用户删除失败");
        }
    }

    @Override
    public boolean isUsernameExists(String account) {
        return userMapper.countByUsername(account) > 0;
    }

    @Override
    public boolean isPhoneExists(String phone) {
        return userMapper.countByPhone(phone) > 0;
    }

    @Override
    public boolean isEmailExists(String email) {
        return userMapper.countByEmail(email) > 0;
    }

    // 基础CRUD方法（兼容性）
    @Override
    public int update(User user) {
        return userMapper.update(user);
    }

    @Override
    public User selectById(Integer id) {
        return userMapper.findById(id);
    }

    @Override
    public User findUserById(Integer id) {
        return userMapper.findById(id);
    }

    @Override
    public User findUserById(String account) {
        return userMapper.findByUsername(account);
    }
}
